//
//  NWDownRefresh.swift
//  Weibo01
//
//  Created by 牛威 on 15/12/13.
//  Copyright © 2015年 牛威. All rights reserved.
//

import UIKit
private let NWDownRefreshOffset : CGFloat = -60

class NWDownRefresh: UIRefreshControl {
    
    //重写父类方法
    
    override func endRefreshing() {
        
        super.endRefreshing()
        
        refresh.stopAnimation()
    }
    
    //主动刷新
    
    override func beginRefreshing() {
        
        super.beginRefreshing()
        
        refresh.startAnimation()
        
    }
    
    //MARK: - KVO监听实现
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        
        //frame可以看出,控件始终呆在屏幕上 越往下拉数值越小(负数一直增),往上滑正数一直增,默认y是0
        
        //KVO注一直监听会影响效率 所以要设置条件来监听
        
        //确定临界点 最少两个条件来确定
        
        if frame.origin.y > 0 {
        
          return
        
        }
        
        //判断是否正在刷新
        
        if refreshing {
        
          refresh.startAnimation()
            return
        
        }
        
        
        if frame.origin.y < NWDownRefreshOffset && refresh.isZheng {
            
            refresh.isZheng  = false
        
        }else if frame.origin.y >= NWDownRefreshOffset && !refresh.isZheng{
            
           refresh.isZheng = true


        }
        
//        print(frame)

        
 
    }
    
     //MARK: - 设置刷新逻辑
    
    override init() {
        
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)  //这样修改之后不管是代码加载还是sb加载都可以保证调用方法
        
        setupUI()
    
    
    }
    
    
    private func setupUI(){
        
        //隐藏菊花
        
        self.tintColor  = UIColor.clearColor()
    
        //添加控件

        addSubview(refresh)
        
        //设置布局
        
        refresh.snp_makeConstraints { (make) -> Void in
            
       //这里一定要注意 从xib加载的控件设置自动布局时要指定size,否则位置不正确
            
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refresh.bounds.size)
        }
    
        //如何实现在拖拽的时候再实现监听,如果不加人主队列的话,监听的太早,加入到主队列
        //实现原因:当主队列有任务,就不会调度队列中任务执行
        //让当前运行循环所有任务执行完毕后,运行循环结束前,开始监听
        //方法触发是在下一次运行循环开始!!!
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
            
        }
        
        
    }
    
    //移除监听(一定要写,代码习惯)
    
    deinit {
        
        self.removeObserver(self, forKeyPath: "frame")
        
    }

    
    
    //懒加载控件
    
    private lazy var refresh = NWDownRefreshView.refreshView()
}

//MARK: 刷新视图 负责处理动画

 class  NWDownRefreshView : UIView {
    
    @IBOutlet weak var loadImage: UIImageView!
    
    @IBOutlet weak var loadView: UIView!
    
    @IBOutlet weak var tipImage: UIImageView!
    //MARK: - 加载视图
    
    class func refreshView()-> NWDownRefreshView {
        
        //UINib ios4.0出来的
    
        let s = UINib.init(nibName: "NWDownRefreshView", bundle: nil)
        
        return s.instantiateWithOwner(nil, options: nil).first as! NWDownRefreshView
    

    
    }
    
    //旋转标记
    
    private var isZheng = false {
    
        didSet {
        
         rotateTipImage()
        
        }
    
    
    }
    
    //动画旋转
    
    private func rotateTipImage(){
        
        
        var angel = CGFloat(M_PI)
        
        angel += self.isZheng ? -0.0000001 : 0.0000001

    
      UIView.animateWithDuration(0.5) { () -> Void in
        
        /*
        注意点1 :角度这里要转换类型
        注意点2:旋转动画的特点 1>顺时针优先 :比如你设置旋转180,不管你的角度设置正负,他都会顺时针旋转
                            2>就近原则:如果你要设置旋转360,它会不旋转
        */
        
        
        self.tipImage.transform = CGAffineTransformRotate(self.tipImage.transform, CGFloat(angel))
        
        
        }
    
    
    }
    
    //播放动画
    
    private func startAnimation(){
    
        loadView.hidden = true
        
        //判断动画是否已经被添加到图层上
        
        let key = "transform.rotation"
        
        if loadView.layer.animationForKey(key) != nil {
            
            return
        }
        
        let basic = CABasicAnimation(keyPath: key)
        
        basic.toValue = 2 * M_PI
        
        basic.duration = 1
        
        basic.repeatCount = MAXFLOAT
        
        basic.removedOnCompletion = false
        
        loadImage.layer.addAnimation(basic, forKey: key)
    }
    
    //停止动画
    private func stopAnimation(){
        
        loadView.hidden = false
        
        loadImage.layer.removeAllAnimations()
        
    }
    
    
}


